<template>
  <div class="smart-qa-container">
    <!-- 聊天区域 -->
    <div class="chat-area">
      <el-scrollbar ref="scrollbar" class="message-list">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message', msg.type]"
        >
          <div class="message-avatar">
            <img
                :src="msg.type === 'user' ? userAvatar : aiAvatar"
                class="avatar"
            />
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="sender">{{ msg.type === 'user' ? '您' : modelNames[currentModel] }}</span>
              <span class="time">{{ formatTime(msg.time) }}</span>
            </div>
            <div class="message-text">
              <el-tag
                  v-if="msg.loading"
                  type="info"
                  effect="plain"
                  class="loading-tag"
              >
                <i class="el-icon-loading"></i>
                {{ modelLoadingTexts[currentModel] }}
              </el-tag>
              <pre v-else>{{ msg.text }}</pre>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 输入区域（优化布局） -->
    <div class="input-area">
      <div class="input-wrapper">
        <el-input
            v-model="userInput"
            type="textarea"
            :rows="4"
            placeholder="请输入您的问题（支持换行）"
            resize="none"
            @keyup.enter.native="sendQuestion"
            class="input-box"
        >
        </el-input>

        <div class="button-group">
          <div class="model-selector">
            <el-radio-group v-model="currentModel" size="medium" @change="switchModel">
              <el-radio-button label="local">本地模型</el-radio-button>
              <el-radio-button label="cloud">联网模型</el-radio-button>
              <el-radio-button label="custom">自研模型</el-radio-button>
            </el-radio-group>
          </div>

          <el-button
              type="primary"
              size="medium"
              @click="sendQuestion"
              icon="el-icon-s-promotion"
              class="send-button"
          >
            智能对话
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 模型配置
      modelNames: {
        local: '本地模型',
        cloud: '联网模型',
        custom: '自研模型'
      },
      currentModel: 'local',
      modelStatus: '',
      modelLoadingTexts: {
        local: '本地模型处理中...',
        cloud: '联网查询中，可能需要更长时间...',
        custom: '自研模型深度分析中...'
      },

      // 消息管理
      userInput: '',
      messages: [],
      userAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      aiAvatar: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'
    }
  },

  mounted() {
    this.initComponent()
  },

  methods: {
    initComponent() {
      this.modelStatus = this.getModelStatus(this.currentModel)
    },

    // 切换模型
    switchModel(modelId) {
      this.currentModel = modelId
      this.modelStatus = this.getModelStatus(modelId)
      this.messages = [] // 清空消息
    },

    // 获取模型状态
    getModelStatus(modelId) {
      const statusMap = {
        local: '本地模型：快速响应，适合简单问题',
        cloud: '联网模型：需要网络连接，获取最新信息',
        custom: '自研模型：专业农业知识库，深度分析'
      }
      return statusMap[modelId] || ''
    },

    // 发送问题
    sendQuestion() {
      const question = this.userInput.trim()
      if (!question) return

      // 添加用户消息
      const currentTime = new Date()
      const userMsg = {
        type: 'user',
        text: question,
        time: currentTime
      }
      this.messages.push(userMsg)
      this.userInput = ''

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 添加AI加载消息
      const loadingMsg = {
        type: 'ai',
        text: '',
        time: currentTime,
        loading: true
      }
      this.messages.push(loadingMsg)

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 模拟API调用延迟
      setTimeout(() => {
        // 生成AI回答
        const answer = this.generateModelResponse(this.currentModel, question)

        // 替换加载消息
        const answerMsg = {
          type: 'ai',
          text: answer,
          time: new Date()
        }

        // 找到最后一条AI消息并替换
        const lastIndex = this.messages.length - 1
        if (this.messages[lastIndex].loading) {
          this.messages[lastIndex] = answerMsg
        } else {
          this.messages.push(answerMsg)
        }

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }, 800)
    },

    // 生成模型响应（模拟）
    generateModelResponse(modelId, question) {
      const baseResponses = [
        '这是针对您的问题的专业回答，基于大量数据训练得出。',
        '经过分析，建议如下：...',
        '根据现有知识，可以得出以下结论：...'
      ]

      const modelSpecific = {
        local: '本地模型使用本地知识库快速响应：',
        cloud: '联网模型查询最新数据后回答：',
        custom: '自研农业模型深度分析后得出：'
      }

      return `${modelSpecific[modelId]}\n\n${baseResponses[modelId % baseResponses.length]}\n\n（模拟响应）`
    },

    // 滚动到底部
    scrollToBottom() {
      const scrollbar = this.$refs.scrollbar
      if (scrollbar && scrollbar.wrap) {
        scrollbar.wrap.scrollTop = scrollbar.wrap.scrollHeight
      }
    },

    // 时间格式化
    formatTime(date) {
      const d = new Date(date)
      return `${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style>
.smart-qa-container {
  display: flex;
  flex-direction: column;
  height: 92vh;
  max-height: 92vh;
  background-color: #f5f7fa;
}

/* 聊天区域容器 - 新增白色间隔 */
.chat-area {
  flex: 1;
  padding: 20px; /* 左右内边距 */
  margin: 15px 20px 0; /* 上边距15px + 左右边距20px */
  background-color: #fff; /* 白色背景 */
  border-radius: 4px; /* 圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 阴影效果 */
  overflow: hidden;
}

.message-list {
  height: 100%;
}

.message {
  display: flex;
  margin-bottom: 25px;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 15px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
}

.message-content {
  max-width: 70%;
}

.user .message-content {
  margin-left: auto;
}

.ai .message-content {
  margin-right: auto;
}

.message-header {
  margin-bottom: 8px;
  display: flex;
  align-items: baseline;
}

.sender {
  font-weight: bold;
  margin-right: 10px;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #999;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
}

.message-text pre {
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin: 0;
}

.loading-tag {
  margin-top: 5px;
}

/* 输入区域调整 - 与聊天区域保持一致间距 */
.input-area {
  padding: 20px;
  margin: 0 20px 20px; /* 左右边距20px + 下边距20px */
  border-top: 1px solid #e6e6e6;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-selector {
  flex: 1;
}

.send-button {
  margin-left: 15px;
  white-space: nowrap;
}

.input-box {
  margin-bottom: 10px;
}

/* 修复Element UI 2.x的滚动条样式 */
.el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
